import 'package:dio/dio.dart';

enum AbsNetworkHostType {
  HTTP,
  HTTPS,
}

class AbsNetwork {
  static AbsNetworkHostType _type;
  static String _host;
  static int _port;
  static var _dio = Dio();

  static void setHost(AbsNetworkHostType type, String host, int port) {
    _type = type;
    _host = host;
    _port = port;

    var preString = _type == AbsNetworkHostType.HTTP ? 'http://' : 'https://';
    _dio.options.baseUrl =
        _port != null ? '$preString$_host:$_port' : '$preString$_host';
    _dio.options.headers['Accept'] = 'application/json';
  }

  static void post(String path,
      {Map<String, dynamic> params,
      void Function(Map<String, dynamic>) success,
      void Function(int, String) failed}) async {
    if (_dio.options.baseUrl == null || _dio.options.baseUrl.isEmpty) {
      failed(-999, 'AbsNetwork must be initialzite before using post method!');
    } else {
      var response = await _dio.post(path, data: params);
      var code = response.statusCode;
      var errMsg = response.statusMessage;
      if (code == 200) {
        success(response.data);
      } else {
        failed(code, errMsg);
      }
    }
  }
}
